package com.sh.dc.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSON;
import com.sh.dc.common.BaseResult;
import com.sh.dc.common.enums.BizCodeEnum;
import com.sh.dc.common.pojo.bo.SolverSaveBO;
import com.sh.dc.common.pojo.dto.SolverDto;
import com.sh.dc.common.pojo.query.SolverPageQuery;
import com.sh.dc.entity.ProductSource;
import com.sh.dc.entity.Solver;
import com.sh.dc.service.IProductSourceService;
import com.sh.dc.service.ISolverService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * <p>
 * 求解器表 前端控制器
 * </p>
 *
 * @author zhenlan
 * @since 2024-07-15
 */
@RestController
@RequestMapping("/solver")
public class SolverController {

    @Autowired
    private ISolverService solverService;

    @Autowired
    private IProductSourceService productSourceService;

    @PostMapping("/save")
    public BaseResult save(@Valid @RequestBody SolverSaveBO solverSaveBO) {
        Solver solver = new Solver();
        BeanUtil.copyProperties(solverSaveBO, solver);
        solver.setUpdateTime(new Date());
        if (CollectionUtil.isNotEmpty(solverSaveBO.getEnvList())) {
            solver.setEnvs(JSON.toJSONString(solverSaveBO.getEnvList()));
        }
        if (CollectionUtil.isNotEmpty(solverSaveBO.getFileParams())) {
            solver.setFileParams(JSON.toJSONString(solverSaveBO.getFileParams()));
        }
        if (CollectionUtil.isNotEmpty(solverSaveBO.getCmdParams())) {
            solver.setCmdParams(JSON.toJSONString(solverSaveBO.getCmdParams()));
        }
        return BaseResult.success(solverService.saveOrUpdate(solver));
    }

    @GetMapping("/{id}")
    public BaseResult getById(@PathVariable("id") Long id) {
        Solver solver = solverService.getById(id);
        if (solver == null) {
            return BaseResult.fail(BizCodeEnum.DATA_NOT_EXISTED);
        }
        SolverDto solverDto = solverService.transferToDto(solver);
        if (solver.getProductSourceId() != null) {
            ProductSource productSource = productSourceService.getById(solver.getProductSourceId());
            if (productSource == null) {
                return BaseResult.fail(BizCodeEnum.PRODUCT_NOT_EXISTED);
            }
            solverDto.setImage(productSource.getRegistry() + "/" + productSource.getNamespace() + "/" + solver.getProduct());
        }
        return BaseResult.success(solverDto);
    }

    @PostMapping("/delete/{id}")
    public BaseResult deleteById(@PathVariable("id") Long id) {
        // TODO 查询是否有任务正在使用该求解器
        return BaseResult.success(solverService.removeById(id));
    }

    @PostMapping("/page")
    public BaseResult page(@Valid @RequestBody SolverPageQuery pageQuery) {
        return BaseResult.success(solverService.getSolverPage(pageQuery));
    }

}
